import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, ImageBackground, Image, TouchableOpacity, Dimensions, Alert, Platform } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { useNavigation } from '@react-navigation/native';
import * as AppleAuthentication from 'expo-apple-authentication';

import { Colors } from '../constants/colors';
import PrimaryButton from '../components/PrimaryButton';
import { AuthManager } from '../utils/api';
import { authService, profileService } from '../services';
import { GoogleAuthWrapper } from '../utils/googleAuthWrapper';


export default function AuthLandingScreen() {
  const nav = useNavigation<any>();
  const images = [
    require('../../assets/swiper-1.jpg'),
    require('../../assets/swiper-2.jpg'),
    require('../../assets/swiper-3.jpg'),
  ];
  const [idx, setIdx] = useState(0);
  const [loading, setLoading] = useState(false);

  // 检查用户认证状态并导航到正确页面
  const checkUserStatusAndNavigate = async () => {
    try {
      const profile = await profileService.getProfile();
      console.log('用户资料:', profile);

      // 如果auditState为null或undefined，说明用户还没有提交认证信息
      if (profile.auditState === null || profile.auditState === undefined) {
        console.log('用户未认证，跳转到个人中心');
        nav.reset({
          index: 0,
          routes: [{ name: 'MainTabs' }],
        });
      } else {
        // 用户已提交认证信息，正常跳转到主页面
        console.log('用户已认证，跳转到主页面');
        nav.reset({
          index: 0,
          routes: [{ name: 'MainTabs' }],
        });
      }
    } catch (error) {
      console.error('获取用户资料失败:', error);
      // 如果获取用户资料失败，也跳转到主页面
      nav.reset({
        index: 0,
        routes: [{ name: 'MainTabs' }],
      });
    }
  };

  useEffect(() => {
    const id = setInterval(() => setIdx((i) => (i + 1) % images.length), 3000);
    return () => clearInterval(id);
  }, []);

  // Apple登录处理
  const handleAppleLogin = async () => {
    setLoading(true);
    try {
      // 检查Apple登录是否可用
      const isAvailable = await AppleAuthentication.isAvailableAsync();
      if (!isAvailable) {
        Alert.alert('錯誤', 'Apple登錄在此設備上不可用');
        return;
      }

      // 执行Apple登录
      const credential = await AppleAuthentication.signInAsync({
        requestedScopes: [
          AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
          AppleAuthentication.AppleAuthenticationScope.EMAIL,
        ],
      });

      console.log('Apple登录凭证:', credential);

      // 检查是否获取到必要的凭证
      if (!credential.identityToken) {
        Alert.alert('登錄失敗', 'Apple登錄失敗：未獲取到有效憑證');
        return;
      }

      // 发送到后端验证
      const result = await authService.appleLogin({
        idToken: credential.identityToken,
      });

      // 检查后端返回结果
      if (!result || !result.token) {
        Alert.alert('登錄失敗', result?.message || 'Apple登錄失敗：服務器未返回有效令牌');
        return;
      }

      // 保存token
      await AuthManager.setToken(result.token);
      console.log('Apple登录Token保存完成:', result.token);

      // 只有在成功获取到token后才显示成功消息
      Alert.alert('成功', result.message || 'Apple登錄成功', [
        {
          text: '確定',
          onPress: () => checkUserStatusAndNavigate(),
        },
      ]);
    } catch (error: any) {
      console.error('Apple登錄失敗:', error);
      if (error.code === 'ERR_CANCELED') {
        // 用户取消登录，不显示错误
        return;
      }
      Alert.alert('登錄失敗', error.message || 'Apple登錄失敗');
    } finally {
      setLoading(false);
    }
  };

  // Google登錄处理
  const handleGoogleLogin = async () => {
    setLoading(true);
    try {
      // 使用包装器处理Google登錄
      const result = await GoogleAuthWrapper.signIn() as any;
      console.log(result,'result')
      // 发送到后端验证
      const authResult = await authService.googleLogin({
        idToken: result.idToken,
      });

      // 保存token
      if (authResult.token) {
        await AuthManager.setToken(authResult.token);
        console.log('Google登錄Token保存完成:', authResult.token);
      }

      Alert.alert('成功', authResult.message || 'Google登錄成功', [
        {
          text: '確定',
          onPress: () => checkUserStatusAndNavigate(),
        },
      ]);
    } catch (error: any) {
      console.error('Google登錄失敗:', error);
      if (error.message === '用户取消') {
        // 用户取消，不显示错误
        return;
      }
      Alert.alert('登錄失敗', error.message || 'Google登錄失敗');
    } finally {
      setLoading(false);
    }
  };


  const { width, height } = Dimensions.get('window');

  return (
    <View style={styles.bg}>
      {/* 背景三圖淡入淡出 */}
      {images.map((imageSource, i) => (
        <ImageBackground
          key={i}
          source={imageSource}
          style={[StyleSheet.absoluteFillObject, i === idx ? { display: 'flex' } : { display: 'none' }]}
          imageStyle={{ opacity: 0.85, resizeMode: 'cover' }}
        />
      ))}

      <SafeAreaView style={[styles.overlay, StyleSheet.absoluteFillObject]}>
        <View style={styles.logoWrap}>
          <View style={styles.logoCard}>
            <Image
              source={require('../../assets/icon.png')}
              style={{ width: 100, height: 100, borderRadius: 20 }}
              resizeMode="contain"
            />
          </View>
        </View>

        <View style={styles.dots}>
          {images.map((_, i) => (
            <View key={i} style={[styles.dot, i === idx && styles.dotActive]} />
          ))}
        </View>

        {Platform.OS === 'ios' && (
          <PrimaryButton
            title={loading ? "登錄中..." : "Apple 登錄"}
            onPress={handleAppleLogin}
            disabled={loading}
            leftIcon={<Ionicons name="logo-apple" size={18} color={Colors.white} />}
          />
        )}

        <View style={{ flexDirection: 'row', marginTop: 12 }}>
          <TouchableOpacity
            style={[styles.whiteBtn, { flex: 1, marginRight: 12, opacity: loading ? 0.6 : 1 }]}
            onPress={handleGoogleLogin}
            disabled={loading}
          >
            <Ionicons name="logo-google" size={18} color={Colors.black} style={{ marginRight: 8 }} />
            <Text style={styles.whiteBtnText}>{loading ? "登錄中..." : "Google 登錄"}</Text>
          </TouchableOpacity>
          <TouchableOpacity style={[styles.whiteBtn, { flex: 1 }]} onPress={() => nav.navigate('EmailLogin') }>
            <Ionicons name="mail-outline" size={18} color={Colors.black} style={{ marginRight: 8 }} />
            <Text style={styles.whiteBtnText}>電郵登錄</Text>
          </TouchableOpacity>
        </View>

        <View style={styles.footerRow}>
          <Text style={{ color: Colors.white, opacity: 0.9 }}>沒有帳號？</Text>
          <TouchableOpacity onPress={() => nav.navigate('SignUp')} >
            <Text style={{ color: Colors.primaryLight, fontWeight: '700' }}> 去註冊 {'>'}</Text>
          </TouchableOpacity>
        </View>
      </SafeAreaView>
    </View>
  );
}

const styles = StyleSheet.create({
  bg: { flex: 1 },
  overlay: { flex: 1, padding: 20, justifyContent: 'flex-end' },
  logoWrap: { flex: 1, alignItems: 'center', justifyContent: 'center' },
  logoCard: {
    width: 180,
    height: 180,
    borderRadius: 28,
    backgroundColor: 'rgba(255,255,255,0.9)',
    alignItems: 'center',
    justifyContent: 'center',
  },
  dots: { flexDirection: 'row', alignSelf: 'center', marginBottom: 16 },
  dot: { width: 6, height: 6, borderRadius: 3, backgroundColor: 'rgba(255,255,255,0.5)', marginHorizontal: 3 },
  dotActive: { width: 28, borderRadius: 3, backgroundColor: Colors.white },
  outlineBtn: {
    height: 56,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: 'rgba(255,255,255,0.6)',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: 16,
  },
  outlineText: { color: Colors.white, fontSize: 16, fontWeight: '600' },
  whiteBtn: {
    height: 56,
    borderRadius: 12,
    backgroundColor: Colors.white,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },
  whiteBtnText: { color: Colors.black, fontSize: 16, fontWeight: '600' },
  footerRow: { flexDirection: 'row', alignSelf: 'center', marginTop: 16 },
});

